package com.example.service;

import com.example.mapper.UsersMapper;
import com.example.mapper.UserMapper;
import com.example.entity.User;
import com.example.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class RegistrationService {
    
    private static final Logger logger = LoggerFactory.getLogger(RegistrationService.class);
    
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AuthService authService;

    @Transactional(rollbackFor = Exception.class)
    public void registerUser(User user) {
        // 参数验证
        validateUserInput(user);
        
        try {
            // 检查手机号是否已存在
            User existingUser = userMapper.findByPhone(user.getPhone());
            if (existingUser != null) {
                throw new BusinessException.DuplicateDataException("该手机号已被注册");
            }
            
            // 检查用户名是否已存在
            User existingUserByUsername = usersMapper.findByUsername(user.getUsername());
            if (existingUserByUsername != null) {
                throw new BusinessException.DuplicateDataException("该用户名已被注册");
            }
            
            // 验证密码强度
            if (!authService.isPasswordStrong(user.getPassword())) {
                throw new BusinessException.ValidationException("密码强度不足，密码长度至少6位");
            }
            
            // 加密密码
            String encodedPassword = authService.encodePassword(user.getPassword());
            user.setPassword(encodedPassword);
            
            // 插入用户
            usersMapper.insertUser(user);
            logger.info("用户注册成功：{}", user.getUsername());
            
        } catch (BusinessException e) {
            logger.warn("用户注册失败：{}", e.getMsg());
            throw e;
        } catch (Exception e) {
            logger.error("用户注册过程中发生异常", e);
            throw new BusinessException("注册失败，请稍后重试", e);
        }
    }
    
    private void validateUserInput(User user) {
        if (user == null) {
            throw new BusinessException.ValidationException("用户信息不能为空");
        }
        if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
            throw new BusinessException.ValidationException("用户名不能为空");
        }
        if (user.getPhone() == null || user.getPhone().trim().isEmpty()) {
            throw new BusinessException.ValidationException("手机号不能为空");
        }
        if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
            throw new BusinessException.ValidationException("密码不能为空");
        }
        
        // 验证手机号格式
        if (!isValidPhoneNumber(user.getPhone())) {
            throw new BusinessException.ValidationException("手机号格式不正确");
        }
        
        // 验证用户名长度
        if (user.getUsername().length() < 2 || user.getUsername().length() > 20) {
            throw new BusinessException.ValidationException("用户名长度应在2-20个字符之间");
        }
    }
    
    private boolean isValidPhoneNumber(String phone) {
        // 简单的手机号验证（11位数字）
        return phone != null && phone.matches("^1[3-9]\\d{9}$");
    }
}